package com.springcloud.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.springcloud.commons.result.Tree;
import com.springcloud.commons.utils.PageInfo;
import com.springcloud.mapper.SysRoleMapper;
import com.springcloud.mapper.SysRoleResourceMapper;
import com.springcloud.mapper.SysUserRoleMapper;
import com.springcloud.model.SysRole;
import com.springcloud.model.SysRoleResource;
import com.springcloud.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * SysRole 表数据服务层接口实现类
 *
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

	 	@Autowired
	    private SysRoleMapper roleMapper;
	    @Autowired
	    private SysUserRoleMapper userRoleMapper;
	    @Autowired
	    private SysRoleResourceMapper roleResourceMapper;

	    @Override
	    public List<Long> selectRoleIdListByUserId(Long userId) {
	        return userRoleMapper.selectRoleIdListByUserId(userId);
	    }

	    @Override
	    public List<Map<Long, String>> selectRoleResourceListByRoleId(Long roleId) {
	        return roleMapper.selectResourceListByRoleId(roleId);
	    }

	    @Override
	    public void selectDataGrid(PageInfo pageInfo) throws DataAccessException{

				Page<SysRole> page = new Page<SysRole>(pageInfo.getNowpage(), pageInfo.getSize());
				List<SysRole> list = roleMapper.selectRoleList(page, pageInfo.getSort(), pageInfo.getOrder());
				pageInfo.setRows(list);
				pageInfo.setTotal((int) page.getTotal());


	    }

	    @Override
	    public Object selectTree() {
	        List<Tree> trees = new ArrayList<Tree>();
	        List<SysRole> roles = roleMapper.selectAll();
	        for (SysRole role : roles) {
	            Tree tree = new Tree();
	            tree.setId(role.getId());
	            tree.setText(role.getName());

	            trees.add(tree);
	        }
	        return trees;
	    }

	    @Override
	    public List<Long> selectResourceIdListByRoleId(Long id) {
	        return roleMapper.selectResourceIdListByRoleId(id);
	    }

	    @Override
	    public void updateRoleResource(Long roleId, String resourceIds) {
	        // 先删除后添加,有点爆力
	    	SysRoleResource roleResource = new SysRoleResource();
	        roleResource.setRoleId(roleId);
	        roleResourceMapper.deleteById(roleResource);

	        String[] resourceIdArray = resourceIds.split(",");
	        for (String resourceId : resourceIdArray) {
	            roleResource = new SysRoleResource();
	            roleResource.setRoleId(roleId);
	            roleResource.setResourceId(Long.parseLong(resourceId));
	            roleResourceMapper.insert(roleResource);
	        }
	    }

}